package com.neu.tlias.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neu.tlias.pojo.Emp;
import com.neu.tlias.pojo.Result;
import com.neu.tlias.service.IEmpService;
import com.neu.tlias.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@Api(tags = "用户登录管理接口")
@Slf4j
@RestController
@RequiredArgsConstructor
public class LoginController {

    private final IEmpService empService;

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("员工登录:{}",emp);
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getUsername,emp.getUsername())
                .eq(Emp::getPassword,emp.getPassword());
        Emp e = empService.getOne(queryWrapper);
        //登录成功，生成令牌，下发令牌
        if(e != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",e.getId());
            claims.put("name",e.getName());
            claims.put("username",e.getUsername());
            //JwtUtils.generateJwt(claims);
            String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息
            return Result.success(jwt);
        }

        //登录失败，返回错误信息
        //return e != null ? Result.success() :Result.error("用户名或密码错误");
        return Result.error("用户名或密码错误");
        //return Result.success();
    }
}
